/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet.tetris;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import sirtet.PieceFactory;

/**
 * A factory that creates instances of TetrisPiece
 * @author guangwei.zhu
 */
public class TetrisPieceFactory extends PieceFactory {

    // This class is only for factories
    protected static class RawTetrisPiece extends TetrisPiece {
        // Expose constructor
        public RawTetrisPiece(int size) {
            super(size);
        }

        // Expose data
        public Object[][] exposeData() {
            return this.pieceData;
        }

        // Expose align()
        @Override
        public void align() {
            super.align();
        }
    }

    /**
     * Construct a TetrisPiece from its string representation
     * @param data A string representation of a TetrisPiece
     * @return The constructed TetrisPiece
     */
    public TetrisPiece fromString(String data) {
        int val, size = 0;
        int i, j;
        Object[][] piece_data;
        ArrayList<Integer> blocks = new ArrayList<Integer>();
        Iterator<Integer> iter;
        RawTetrisPiece piece;

        for (i = 0; i < data.length(); i++) {
            val = Integer.valueOf(data.substring(i, i + 1));     // Cast to numbers
            if (val != TetrisPiece.EMPTY) {
                size++;
            }
            blocks.add(val);
        }

        // Build the piece
        piece = new RawTetrisPiece(size);
        piece_data = piece.exposeData();

        // Fill in the data
        iter = blocks.iterator();
        for (i = 0; i < size; i++) {
            for (j = 0; j < size; j++) {
                if (iter.hasNext()) {
                    piece_data[i][j] = iter.next();
                } else {
                    piece_data[i][j] = TetrisPiece.EMPTY;
                }
            }
        }

        return (TetrisPiece) piece;
    }

    /**
     * Construct multiple TetrisPieces from a file
     * @param file A file object containing the input data
     * @return A list of the constructed TetrisPiece
     */
    public List<TetrisPiece> fromFile(File file)
            throws IOException, FileNotFoundException {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        ArrayList<TetrisPiece> pieces = new ArrayList<TetrisPiece>();
        String str;

        while (br.ready()) {
            str = br.readLine();
            if (str.isEmpty()) {
                break;
            }
            pieces.add(this.fromString(str));
        }

        return (List<TetrisPiece>) pieces;
    }
}
